package com.tchcn.supermarket.ui.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fanwe.library.adapter.http.model.SDResponse;
import com.tchcn.library.http.AppRequestCallback;
import com.tchcn.library.model.BaseActModel;
import com.tchcn.library.model.UserInfoModel;
import com.tchcn.library.utils.LogUtil;
import com.tchcn.supermarket.R;
import com.tchcn.supermarket.adapter.BackManageGoodsAdapter;
import com.tchcn.supermarket.adapter.BackstageGoodsTypeAdapter;
import com.tchcn.supermarket.base.BaseRecyclerAdapter;
import com.tchcn.supermarket.base.SBaseFragment;
import com.tchcn.supermarket.common.SCommonInterface;
import com.tchcn.supermarket.model.GoodTypeActModel;
import com.tchcn.supermarket.model.StockListActModel;
import com.tchcn.supermarket.utils.AnimationUtil;
import com.tchcn.supermarket.utils.SDToast;
import com.tchcn.supermarket.utils.ViewBinder;

import java.util.ArrayList;
import java.util.List;

/**
 *  后台管理-商品管理
 * Created by humu on 2018/5/26.
 */

public class GoodsManageFragment extends SBaseFragment {

    private static GoodsManageFragment fragment;
    //对应类型的商品列表
    private RecyclerView rv_goods;
    //商品类型列表
    private RecyclerView rv_types;
    //新增/编辑商品分类
    private LinearLayout ll_add_good_type;
    private TextView tv_gtd_title;
    private EditText et_gt_name;
    private TextView tv_type_name;

    private BackstageGoodsManageFragment parentFragment;
    private View view_mask;
    //当前编辑的商品分类id
    private String editGoodTypeId = "";
    private int currentGoodTypeIndex = 0; //当前商品类型索引，默认0
    private String selectedGoodTypeId = ""; //选中的商品类型id
    private BackstageGoodsTypeAdapter typeAdapter;
    private BackManageGoodsAdapter adapter;
    private EditText et_keyword;

    public static GoodsManageFragment getInstance(){
        if(fragment == null){
            fragment = new GoodsManageFragment();
        }
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.sfragment_goods_manage;
    }

    @Override
    protected void initView() {
        initUI();
        initGoodTypes();
    }

    public void getGoodsByType(){
        String keyword = et_keyword.getText().toString();
        SCommonInterface.getStockList(activity.getLocationId(), selectedGoodTypeId,
                keyword, "", "", new AppRequestCallback<StockListActModel>() {
                    @Override
                    protected void onSuccess(SDResponse sdResponse) {
                        LogUtil.e("getStockList",sdResponse.getResult());
                        if(actModel.isOk()){
                            StockListActModel.StockListData data = actModel.getData();
                            if(data != null){
                                List<StockListActModel.StockListData.StockModel> stockModelList = data.getRes();
                                if(stockModelList != null && stockModelList.size() > 0){
                                    adapter.setDatas(stockModelList);
                                }else{
                                    adapter.setDatas(new ArrayList<StockListActModel.StockListData.StockModel>());
                                }
                            }else{
                                adapter.setDatas(new ArrayList<StockListActModel.StockListData.StockModel>());
                            }
                        }else{
                            adapter.setDatas(new ArrayList<StockListActModel.StockListData.StockModel>());
                        }
                    }
                });

    }

    private void initGoodTypes() {
        SCommonInterface.getAllTables(activity.getLocationId(), new AppRequestCallback<GoodTypeActModel>() {
            @Override
            protected void onSuccess(SDResponse sdResponse) {
                if(actModel.isOk()){
                    GoodTypeActModel.GoodTypeData data = actModel.getData();
                    if(data != null){
                        List<GoodTypeActModel.GoodTypeData.GoodType> goodTypeList = data.getRes();
                        if(goodTypeList != null && goodTypeList.size()>0){
                            goodTypeList.get(currentGoodTypeIndex).setChecked(true);
                            selectedGoodTypeId = goodTypeList.get(currentGoodTypeIndex).getId();
                            ViewBinder.setTextView(tv_type_name,goodTypeList.get(0).getName());
                            typeAdapter.setDatas(goodTypeList);
                            getGoodsByType();
                        }
                    }
                }
            }
        });
    }

    private void initUI() {
        parentFragment = (BackstageGoodsManageFragment) getParentFragment();
        rv_goods = find(R.id.rv_goods);
        rv_types = find(R.id.rv_types);

        TextView tv_add_good = find(R.id.tv_add_good);
        tv_add_good.setOnClickListener(this);
        rv_types.setLayoutManager(new LinearLayoutManager(context));
        rv_goods.setLayoutManager(new GridLayoutManager(context,4));
        Button btn_new_classification = find(R.id.btn_new_classification);
        btn_new_classification.setOnClickListener(this);

        ll_add_good_type = find(R.id.ll_add_good_type);
        view_mask = find(R.id.view_mask);
        view_mask.setOnClickListener(this);
        tv_gtd_title = find(R.id.tv_gtd_title);
        et_gt_name = find(R.id.et_gt_name);
        TextView tv_gtd_cancel = find(R.id.tv_gtd_cancel);
        tv_gtd_cancel.setOnClickListener(this);
        TextView tv_gtd_confirm = find(R.id.tv_gtd_confirm);
        tv_gtd_confirm.setOnClickListener(this);
        tv_type_name = find(R.id.tv_type_name);
        Button btn_del_type = find(R.id.btn_del_type);
        btn_del_type.setOnClickListener(this);
        et_keyword = find(R.id.et_keyword);
        et_keyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getGoodsByType();
            }
        });

        typeAdapter = new BackstageGoodsTypeAdapter(0);
        typeAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<GoodTypeActModel.GoodTypeData.GoodType>() {
            @Override
            public void onItemClick(View covertView, int position, GoodTypeActModel.GoodTypeData.GoodType data) {
                typeAdapter.getItem(currentGoodTypeIndex).setChecked(false);
                data.setChecked(true);
                currentGoodTypeIndex = position;
                typeAdapter.notifyDataSetChanged();
                selectedGoodTypeId = data.getId();
                ViewBinder.setTextView(tv_type_name,data.getName());
                getGoodsByType();
            }
        });
        rv_types.setAdapter(typeAdapter);

        adapter = new BackManageGoodsAdapter();
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<StockListActModel.StockListData.StockModel>() {
            @Override
            public void onItemClick(View covertView, int position, StockListActModel.StockListData.StockModel data) {
                parentFragment.changeFragment(GoodsManageFragment.this,NewClassificationFragment.getInstance(currentGoodTypeIndex,selectedGoodTypeId,
                        data.getId()));
            }
        });
        rv_goods.setAdapter(adapter);

    }

    private void hideViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
        view_mask.setVisibility(View.GONE);
    }

    private void showViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewAppearAnim());
        view_mask.setVisibility(View.VISIBLE);
    }

    private void hideGoodTypePopup(){
        if(ll_add_good_type.getVisibility() == View.VISIBLE){
            ll_add_good_type.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
            ll_add_good_type.setVisibility(View.GONE);
            et_gt_name.setText("");
        }
        hideViewMask();
    }

    /**
     * 显示新增/编辑分类弹框
     * @param gtdTitle //新增/编辑分类
     * @param goodTypeId //编辑分类传入分类id
     */
    public void showGoodTypePopup(String gtdTitle,String goodTypeId,String editContent){
        editGoodTypeId = goodTypeId;
        if(ll_add_good_type.getVisibility() == View.GONE){
            ll_add_good_type.startAnimation(AnimationUtil.getMaskViewAppearAnim());
            ll_add_good_type.setVisibility(View.VISIBLE);
        }
        ViewBinder.setTextView(tv_gtd_title,gtdTitle);
        ViewBinder.setTextView(et_gt_name,editContent);
        showViewMask();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if(id == R.id.tv_add_good){ //新增商品
            parentFragment.changeFragment(GoodsManageFragment.this,NewClassificationFragment.getInstance(currentGoodTypeIndex,selectedGoodTypeId,
                    ""));
        }else if(id == R.id.view_mask){
            hideGoodTypePopup();
        }else if(id == R.id.btn_new_classification){ //新增分类
            showGoodTypePopup("新增分类","","");
        }else if(id == R.id.tv_gtd_cancel){ //新增商品分类-取消
            hideGoodTypePopup();
        }else if(id == R.id.btn_del_type){ //删除分类
            if(!TextUtils.isEmpty(selectedGoodTypeId)){
                SCommonInterface.delGoodType(UserInfoModel.getUser_id(), selectedGoodTypeId, new AppRequestCallback<BaseActModel>() {
                    @Override
                    protected void onSuccess(SDResponse sdResponse) {
                        if(actModel.isOk()){
                            currentGoodTypeIndex = 0;
                            selectedGoodTypeId = "";
                            initGoodTypes();
                        }
                        SDToast.showToast(context,actModel.getMsg());
                    }
                });
            }
        }else if(id == R.id.tv_gtd_confirm){ //新增商品分类-确定
            String goodTypeName = et_gt_name.getText().toString();
            if(TextUtils.isEmpty(goodTypeName)){
                SDToast.showToast(context,"请输入分类名");
                return;
            }
            if("新增分类".equals(tv_gtd_title.getText().toString())){
                SCommonInterface.addGoodType(UserInfoModel.getUser_id(), activity.getLocationId(), goodTypeName,
                        new AppRequestCallback<BaseActModel>() {
                            @Override
                            protected void onSuccess(SDResponse sdResponse) {
                                if(actModel.isOk()){
                                    initGoodTypes();
                                }
                                SDToast.showToast(context,actModel.getMsg());
                            }

                            @Override
                            protected void onFinish(SDResponse resp) {
                                super.onFinish(resp);
                                hideGoodTypePopup();
                            }
                        });
            }else if("编辑分类".equals(tv_gtd_title.getText().toString())){
                SCommonInterface.updateGoodType(UserInfoModel.getUser_id(), editGoodTypeId, goodTypeName,
                        new AppRequestCallback<BaseActModel>() {
                            @Override
                            protected void onSuccess(SDResponse sdResponse) {
                                if(actModel.isOk()){
                                    initGoodTypes();
                                }
                                SDToast.showToast(context,actModel.getMsg());
                            }

                            @Override
                            protected void onFinish(SDResponse resp) {
                                super.onFinish(resp);
                                hideGoodTypePopup();
                            }
                        });
            }
        }
    }

}
